<template>
  <!-- 租赁规格弹窗 -->
  <su-popup :show="show" round="10" @close="emits('close')">
    <!-- SKU 信息 -->
    <view class="ss-modal-box bg-white ss-flex-col">
      <view class="modal-header ss-flex ss-col-center">
        <view class="header-left ss-m-r-30">
          <image
            class="sku-image"
            :src="state.selectedSku.picUrl || goodsInfo.picUrl"
            mode="aspectFill"
          />
        </view>
        <view class="header-right ss-flex-col ss-row-between ss-flex-1">
          <view class="goods-title ss-line-2">{{ goodsInfo.name }}</view>
          <view class="header-right-bottom ss-flex ss-col-center ss-row-between">
            <view class="ss-flex">
              <view class="price-text">
                {{
                  fen2yuan(
                    state.selectedSku.promotionPrice || state.selectedSku.price || goodsInfo.price,
                  )
                }}
                <text v-if="state.selectedSku.promotionType > 0">
                  <text class="iconBox" v-if="state.selectedSku.promotionType === 4">
                    限时优惠
                  </text>
                  <text class="iconBox" v-else-if="state.selectedSku.promotionType === 6">
                    会员价
                  </text>
                  <text class="origin-price-text">
                    {{ fen2yuan(state.selectedSku.price) }}
                  </text>
                </text>
              </view>
            </view>
            <view class="stock-text ss-m-l-20">
              {{ formatStock('exact', state.selectedSku.stock || goodsInfo.stock) }}
            </view>
          </view>
        </view>
      </view>

      <!-- 属性选择 -->
      <view class="modal-content ss-flex-1">
        <scroll-view scroll-y="true" class="modal-content-scroll" @touchmove.stop>
          <view class="sku-item ss-m-b-20" v-for="property in propertyList" :key="property.id">
            <view class="label-text ss-m-b-20">{{ property.name }}</view>
            <view class="ss-flex ss-col-center ss-flex-wrap">
              <button
                class="ss-reset-button spec-btn"
                v-for="value in property.values"
                :class="[
                  {
                    'ui-BG-Main-Gradient': state.currentPropertyArray[property.id] === value.id,
                  },
                  {
                    'disabled-btn': value.disabled === true,
                  },
                ]"
                :key="value.id"
                :disabled="value.disabled === true"
                @tap="onSelectSku(property.id, value.id)"
              >
                {{ value.name }}
              </button>
            </view>
          </view>
          <!-- 修改：将租赁数量的下边距从 ss-m-b-20 改回 ss-m-b-40，与参考图片中"购买数量"与按钮区域的间距保持一致 -->
          <view class="buy-num-box ss-flex ss-col-center ss-row-between ss-m-b-10">
            <view class="label-text">租赁数量</view>
            <su-number-box
              :min="1"
              :max="state.selectedSku.stock"
              :step="1"
              v-model="state.selectedSku.goods_num"
              @change="onNumberChange($event)"
            />
          </view>
        </scroll-view>
      </view>

      <!-- 操作区 -->
      <view class="modal-footer border-top">
        <view class="buy-box ss-flex ss-row-right">
          <!-- 修改：按钮文字从"立即购买"改为"立即租赁" -->
          <button class="ss-reset-button buy-btn ui-Shadow-Main" @tap="onBuy">立即租赁</button>
        </view>
      </view>
    </view>
  </su-popup>
</template>

<script setup>
  import { computed, reactive, watch } from 'vue';
  import sheep from '@/sheep';
  import { formatStock, convertProductPropertyList, fen2yuan } from '@/sheep/hooks/useGoods';

  const emits = defineEmits(['change', 'buy', 'close']);
  const props = defineProps({
    goodsInfo: {
      type: Object,
      default() {},
    },
    show: {
      type: Boolean,
      default: false,
    },
  });

  const state = reactive({
    selectedSku: {
      id: 0,
      goods_num: 1,
      price: 0,
      stock: 0,
      picUrl: '',
    },
    currentPropertyArray: {},
  });

  const propertyList = convertProductPropertyList(props.goodsInfo.skus || []);
  
  const skuList = computed(() => {
    if (!props.goodsInfo.skus) return [];
    let skuPrices = props.goodsInfo.skus;
    for (let price of skuPrices) {
      price.value_id_array = price.properties?.map((item) => item.valueId) || [];
    }
    return skuPrices;
  });

  // 初始化默认SKU
  function initDefaultSku() {
    if (props.goodsInfo.skus && props.goodsInfo.skus.length > 0) {
      const defaultSku = props.goodsInfo.skus[0];
      state.selectedSku = {
        ...defaultSku,
        goods_num: 1,
      };
    }
  }

  // 选择SKU规格
  function onSelectSku(propertyId, valueId) {
    state.currentPropertyArray[propertyId] = valueId;
    
    // 根据选择的属性找到对应的SKU
    const selectedSku = skuList.value.find(sku => {
      return sku.value_id_array.every(id => 
        Object.values(state.currentPropertyArray).includes(id)
      );
    });

    if (selectedSku) {
      state.selectedSku = {
        ...selectedSku,
        goods_num: state.selectedSku.goods_num || 1,
      };
    }
  }

  watch(
    () => state.selectedSku,
    (newVal) => {
      emits('change', newVal);
    },
    {
      immediate: true,
      deep: true,
    },
  );

  watch(
    () => props.goodsInfo,
    () => {
      initDefaultSku();
    },
    {
      immediate: true,
    }
  );

  function onNumberChange(e) {
    if (e === 0) return;
    if (state.selectedSku.goods_num === e) return;
    state.selectedSku.goods_num = e;
  }

  function onBuy() {
    if (state.selectedSku.id <= 0) {
      sheep.$helper.toast('请选择规格');
      return;
    }
    if (state.selectedSku.stock <= 0) {
      sheep.$helper.toast('库存不足');
      return;
    }
    emits('buy', state.selectedSku);
  }
</script>

<style lang="scss" scoped>
  /* 修改：缩减弹窗高度，从1000rpx减少到500rpx，减少一半 */
  .ss-modal-box {
    border-radius: 30rpx 30rpx 0 0;
    max-height: 690rpx;
    height: 690rpx;
  }

  .modal-header {
    position: relative;
    padding: 80rpx 40rpx 40rpx;

    .sku-image {
      width: 160rpx;
      height: 160rpx;
      border-radius: 10rpx;
    }

    .goods-title {
      font-size: 28rpx;
      font-weight: 500;
      line-height: 42rpx;
    }

    .price-text {
      font-size: 30rpx;
      font-weight: 500;
      color: #ff3000;
      font-family: OPPOSANS;

      &:before {
        content: '¥';
        font-size: 24rpx;
      }
    }

    .origin-price-text {
      font-size: 24rpx;
      color: #c4c4c4;
      text-decoration: line-through;
      margin-left: 8rpx;

      &:before {
        content: '¥';
      }
    }

    .stock-text {
      font-size: 26rpx;
      color: #999999;
    }
  }

  .modal-content {
    padding: 0 40rpx;

    /* 修改：相应调整滚动区域高度，从600rpx减少到300rpx */
    .modal-content-scroll {
      max-height: 300rpx;
      height: 300rpx;
    }

    .label-text {
      font-size: 26rpx;
      font-weight: 500;
      color: #333333;
    }

    .spec-btn {
      height: 60rpx;
      min-width: 100rpx;
      padding: 0 30rpx;
      background: #f4f4f4;
      border-radius: 30rpx;
      color: #434343;
      font-size: 26rpx;
      margin-right: 20rpx;
      margin-bottom: 20rpx;

      &.ui-BG-Main-Gradient {
        background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
        color: #fff;
      }

      &.disabled-btn {
        color: #c6c6c6;
        background: #f8f8f8;
      }
    }

    .buy-num-box {
      .label-text {
        font-size: 28rpx;
      }
    }
  }

  /* 修改：调整modal-footer的上内边距，从20rpx减少到10rpx，进一步优化间距 */
  .modal-footer {
    padding: 10rpx 40rpx 40rpx;

    .buy-box {
      padding: 10rpx 0;

      /* 修改：立即租赁按钮样式，保持原有的宽度356rpx和高度80rpx */
      .buy-btn {
        width: 356rpx;
        height: 80rpx;
        border-radius: 40rpx;
        background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
        color: #fff;
        font-size: 28rpx;
        font-weight: 500;
      }
    }
  }

  .iconBox {
    padding: 2rpx 10rpx;
    font-size: 20rpx;
    background: #ff6000;
    color: #fff;
    border-radius: 4rpx;
    margin-right: 8rpx;
  }
</style>








